package com.nd.controller.wx;

import com.nd.pojo.bean.User;
import com.nd.pojo.vo.wx.BaseRespWXVo;
import com.nd.pojo.vo.wx.IndexUserOrderVo;
import com.nd.pojo.vo.wx.LoginUserInfoVo;
import com.nd.pojo.vo.wx.LoginUserVo;
import com.nd.realm.MallToken;
import com.nd.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("wx")
public class WxUserController {

    @Autowired
    UserService userService;

    @RequestMapping("auth/login")
    public BaseRespWXVo login(@RequestBody User user){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new MallToken(user.getUsername(),user.getPassword(),"wx"));
        }catch (AuthenticationException |NullPointerException e){
            return BaseRespWXVo.fail("账户或密码错误！");
//        }catch (IncorrectCredentialsException e){
//            return BaseRespWXVo.fail("密码错误！");
        }catch (Exception e){
            return BaseRespWXVo.fail("登录异常");
        }
        String id = (String) subject.getSession().getId();
        User resultUser = (User) subject.getPrincipal();
        LoginUserInfoVo loginUserInfoVo = new LoginUserInfoVo(resultUser.getNickname(),resultUser.getAvatar());
        LoginUserVo loginUserVo = new LoginUserVo(loginUserInfoVo,resultUser.getLastLoginTime().toString(),id);
        return BaseRespWXVo.ok(loginUserVo);
    }
    @RequestMapping("auth/logout")
    public BaseRespWXVo logout(){
        Subject subject = SecurityUtils.getSubject();
        if(subject!=null) subject.logout();
        return BaseRespWXVo.ok();
    }


    @RequestMapping("user/index")
    public BaseRespWXVo userIndex(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        IndexUserOrderVo indexUserOrderVo = userService.queryUserIndexVo(user.getId());
        HashMap<String, IndexUserOrderVo> map = new HashMap<>();
        map.put("order",indexUserOrderVo);
        return BaseRespWXVo.ok(map);
    }

}
